package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    Client client;

    @Autowired
    SmsService service;
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public void getCode(@RequestParam String phone) {

        String codeKey = "app:login" + phone;
        //到redis中查询codeKey是否存在
        Boolean isExist = redisTemplate.hasKey(codeKey);
        if (isExist) {
            //若存在时间不足一分钟，响应发送过于频繁。
            //获取验证码有效时间  10分钟
            long codeExpireTime = 600; //(s)
            //获取还剩多少时间
            Long expireSecond = redisTemplate.getExpire(codeKey);
            if (codeExpireTime - expireSecond < 60) {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
            //1.生成验证码
            String verifyCode = VerifyCodeUtil.getVerifyCode(6);
            System.out.println(verifyCode);
            //2.redis保存验证码
            //String codeKey = "app:login"+phone;
            redisTemplate.opsForValue().set(codeKey, verifyCode, 60 * 10, TimeUnit.SECONDS);
            service.sendCode(phone,verifyCode);

    }

    @Override
    public String login(LoginVo loginVo) {

        //手机号
        String phone = loginVo.getPhone();
        //验证码
        String code = loginVo.getCode();
        //判断手机号是否为空
        if (StringUtils.hasText(phone)) {
            new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //判断手机号验证码是否为空
        if (StringUtils.hasText(code)) {
            new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //获取redis验证码
        String codeKey = "app:login" + phone;
        String redisCode = redisTemplate.opsForValue().get(codeKey);
        //验证redis中的code是否过期
        if (!StringUtils.hasText(redisCode)) {
            new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        //验证是否一致
        if (!code.equals(redisCode)) {
            new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        // mysql检查手机号是否存在，如果不存在就保存
        UserInfo userInfo = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("phone", phone));
        if (userInfo == null) {
            UserInfo userInfo1 = new UserInfo();
            userInfo1.setPhone(phone);
            userInfo1.setNickname("用户-"+phone);
            userInfo1.setStatus(BaseStatus.ENABLE);
            userInfoService.save(userInfo1);
        }
        //判断用户是否被禁用
        if (userInfo.getStatus()==BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //给前端发放令牌（token）
        String token = JwtUtil.createToken(userInfo.getId(),userInfo.getPhone());
        return token;
    }

    @Override
    public UserInfoVo getUserInfoById(Long userId) {
        UserInfo userInfo = userInfoService.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());
        return userInfoVo;
    }
}
